using Microsoft.AspNetCore.SignalR.Client;
namespace client
{
    public partial class FormC : Form
    {

        HubConnection connection = new HubConnectionBuilder().Build();
        public FormC()
        {
            InitializeComponent();
          
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            connection= new HubConnectionBuilder()
               .WithUrl("https://localhost:7169/ChatHub")
                .Build();
            connection.Closed += async (error) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);
                await connection.StartAsync();
            };
        }
        
        delegate void SetTextCallBack(string text);
        private void SetText(string text)
        {
            if (this.RichTextBoxConsole.InvokeRequired)
            {
                SetTextCallBack stcb = new SetTextCallBack(SetText);
                this.Invoke(stcb, new object[] { text });
            }
            else
            {
                this.RichTextBoxConsole.Text = text;
            }
        }
        delegate void AppendTextCallBack(string text);
        private void AppendText(string text)
        {
            if (this.RichTextBoxConsole.InvokeRequired)
            {
                AppendTextCallBack stcb = new AppendTextCallBack(SetText);
                this.Invoke(stcb, new object[] { text });
            }
            else
            {
                this.RichTextBoxConsole.AppendText(text);
            }
        }

        private async void button2_Click(object sender, EventArgs e)
        {
            //con
            connection.On<string, string>("ReceiveMessage", (user, message) =>
            {
                
                    var newMessage = $"{user}: {message}";
                    AppendText(newMessage + "\r\n");

            });

            try
            {
                await connection.StartAsync();               
            }
            catch (Exception ex)
            {
                AppendText(ex.Message);
            }
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            //send
            try
            {
                await connection.InvokeAsync("SendMessage", user.Text,msg.Text);
            }
            catch (Exception ex)
            {
                AppendText(ex.Message);
            }
        }

       

        private async void button3_Click(object sender, EventArgs e)
        {
            //discon
            if(connection != null)
            {
               await connection.StopAsync();
               await connection.DisposeAsync();
            }
        }
    }
}